#include "fileop.h"
#include <stdlib.h>
#include <string.h>

static FILE *open_file(const char *filename, const char *mode)
{
    FILE *fp = fopen(filename, mode);
    if (!fp)
        perror("Failed to open file");
    return fp;
}

static void close_file(FILE *fp)
{
    if (fp)
        fclose(fp);
}

static void read_file_content(FILE *fp, char **content)
{
    fseek(fp, 0, SEEK_END);
    long size = ftell(fp);
    fseek(fp, 0, SEEK_SET);
    *content = malloc(size + 1);
    if (*content)
    {
        fread(*content, 1, size, fp);
        (*content)[size] = '\0';
    }
}

static void copy_file_content(FILE *src, FILE *dest)
{
    int ch;
    while ((ch = fgetc(src)) != EOF)
    {
        fputc(ch, dest);
    }
}

void file_operation(int mode, char *filename, void *content)
{
    char **content_ptr = (char **)content;
    FILE *fp = NULL, *dest_fp = NULL;

    switch (mode)
    {
    case 1: // 写入
        if ((fp = open_file(filename, "w")))
        {
            fputs((char *)content, fp);
            close_file(fp);
        }
        break;

    case 2: // 读取
        if ((fp = open_file(filename, "r")))
        {
            read_file_content(fp, content_ptr);
            close_file(fp);
        }
        break;

    case 3: // 追加
        if ((fp = open_file(filename, "a")))
        {
            fputs((char *)content, fp);
            close_file(fp);
        }
        break;

    case 4: // 删除
        remove(filename);
        break;

    case 5: // 复制
        if ((fp = open_file(filename, "r")) &&
            (dest_fp = open_file((char *)content, "w")))
        {
            copy_file_content(fp, dest_fp);
            close_file(dest_fp);
            close_file(fp);
        }
        break;

    case 6: // 硬件写入
        if ((fp = open_file(filename, "w")) && content)
        {
            fwrite(content, sizeof(struct input_event), 1, fp);
            close_file(fp);
        }
        break;
    }
}

void write_file(char *filename, char *content)
{
    file_operation(1, filename, content);
}

char *read_file(char *filename)
{
    char *content = NULL;
    file_operation(2, filename, &content);
    return content;
}

void append_file(char *filename, char *content)
{
    file_operation(3, filename, content);
}

void delete_file(char *filename)
{
    file_operation(4, filename, NULL);
}

void copy_file(char *src, char *dest)
{
    file_operation(5, src, dest);
}

void write2_file(char *filename, void *content)
{
    file_operation(6, filename, content);
}
